package com.campus.service.Impl;


import com.campus.domain.Dto.UserLoginDto;
import com.campus.domain.Dto.UserRegisterDto;
import com.campus.domain.Vo.UserSelectVo;
import com.campus.mapper.RoleMapper;
import com.campus.mapper.UserMapper;
import com.campus.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Integer register(UserRegisterDto userRegisterDto) {

        Long userId = 0l;
        Integer rs = 0;

        //先插入user表
        try {
            userId = userMapper.addUser(userRegisterDto);
        }catch (Exception e){
            e.printStackTrace();
            log.info("userId failed");
            //需要抛出异常，使事务生效
            throw new RuntimeException();
        }
        //如果userId不对，返回0
        if(userId == null || userId == 0l){
            return rs;
        }
        //在循环插入user_role表
        try {
            List<Long> roleIds = userRegisterDto.getRoleId();
            for (Long roleId:roleIds) {
                rs = roleMapper.addUserRole(userId,roleId);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.info("roleId failed");
            throw new RuntimeException();
        }

        //主键返回为空或0
        return rs;
    }

    @Override
    public UserLoginDto login(String loginName, String password) {
        return userMapper.selectOne(loginName,password);
    }

    @Override
    public UserSelectVo select(String loginName, Long id) {
        return userMapper.selectByNameOrId(loginName,id);
    }
}
